<template>
  <div style="margin:10px 20px 0 20px">
    <el-tabs v-model="runHandleName" type="border-card" @tab-click="handleClick">
      <el-tab-pane label="管理用例集" name="first">
        <div style="float: left;margin-left: 1.5%;">
          <el-input v-model="dataForm.demoname" placeholder="请输入测试集名称" style="width: 200px;" class="filter-item" @keyup.native="handleFilter" />
        </div>
        <div style="float: left;margin-left: 1.5%;margin-bottom: 6px;">
          <el-button type="danger" @click="batchrunHandle">批量删除</el-button>
        </div>
        <el-table
          border
          highlight-current-row
          :data="runHandletablepageData"
          style="width: 98%;left: 1.5%;"
          @selection-change="selectRowHandle"
          @sort-change="runHandletableSortChange"
        >
          <el-table-column
            type="selection"
            align="center"
            width="55"
          />
          <el-table-column
            prop="id"
            label="ID"
            align="center"
            sortable
            min-width="90"
          />
          <el-table-column
            prop="set_name"
            sortable
            align="center"
            :show-overflow-tooltip="true"
            label="测试集名称"
            min-width="180"
          />
          <el-table-column
            prop="case_count"
            sortable
            align="center"
            :show-overflow-tooltip="true"
            label="测试用例"
            min-width="180"
          >
            <template slot-scope="{ row }">
              <router-link :to="{ path: '/caseSet/caseSetManager/' + row.id + '/' + row.set_name}">
                <el-tag style="cursor: pointer;" :type="row.case_count === 0 || row.case_count === '' ? 'info' : ''">{{ row.case_count === '' ? 0 : row.case_count }}</el-tag>
              </router-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="create_time"
            sortable
            align="center"
            :show-overflow-tooltip="true"
            label="创建时间"
            min-width="180"
          />
          <el-table-column
            prop="testdata_set"
            sortable
            align="center"
            :show-overflow-tooltip="true"
            label="测试数据"
            min-width="180"
          >
            <template slot-scope="scope">
              <template v-if="scope.row.testdata_set === ''|| scope.row.testdata_set === '{}'">
                <el-button type="primary" icon="el-icon-edit" circle @click="testdatalog(scope.row)" />
              </template>
              <el-link v-else :underline="false"><span class="setting-data" @click="testdatalog(scope.row)">{{ scope.row.testdata_set }}</span></el-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="mark"
            sortable
            align="center"
            :show-overflow-tooltip="true"
            label="备注"
            min-width="180"
          />
          <el-table-column label="操作" fixed="right" header-align="center" align="center" min-width="160">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="deleterunHand(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block" style="margin-left: 1.5%;">
          <el-pagination
            :current-page="pageIndex"
            :page-sizes="[10, 15, 30, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="runHandletabletotal"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
      <el-tab-pane label="添加用例集" name="second">
        <div style="float: left;margin-left: 1.5%;">
          <el-input v-model="dataForm.demoname" placeholder="请输入元素名称" style="width: 200px;" class="filter-item" @keyup.native="runaddtablepageFilter" />
        </div>
        <div style="float: left;margin-left: 1.5%;margin-bottom: 6px;">
          <el-button type="danger" @click="batchaddHandle">批量添加</el-button>
        </div>
        <el-table
          border
          highlight-current-row
          :data="runaddtablepageData"
          style="width: 98%;left: 1.5%;"
          @selection-change="selectRowHandle"
          @sort-change="runaddtableSortChange"
        >
          <el-table-column
            type="selection"
            align="center"
            width="55"
          />
          <el-table-column
            prop="id"
            label="ID"
            align="center"
            sortable
            min-width="90"
          />
          <el-table-column
            prop="set_name"
            sortable
            align="center"
            :show-overflow-tooltip="true"
            label="测试集名称"
            min-width="180"
          />
          <el-table-column
            prop="case_count"
            sortable
            align="center"
            :show-overflow-tooltip="true"
            label="测试用例"
            min-width="180"
          >
            <template slot-scope="{ row }">
              <router-link :to="{ path: '/caseSet/caseSetManager/' + row.id + '/' + row.set_name}">
                <el-tag style="cursor: pointer;" :type="row.case_count === 0 || row.case_count === '' ? 'info' : ''">{{ row.case_count === '' ? 0 : row.case_count }}</el-tag>
              </router-link>
            </template>
          </el-table-column>
          <el-table-column
            prop="create_time"
            sortable
            align="center"
            :show-overflow-tooltip="true"
            label="创建时间"
            min-width="180"
          />
          <el-table-column
            prop="mark"
            sortable
            align="center"
            :show-overflow-tooltip="true"
            label="备注"
            min-width="180"
          />
          <el-table-column label="操作" fixed="right" header-align="center" align="center" min-width="160">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="runHandleOK(scope.row)">添加</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="block" style="margin-left: 1.5%;">
          <el-pagination
            :current-page="pageIndex"
            :page-sizes="[10, 15, 30, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="runaddletabletotal"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!--测试数据编辑页面 start-->
    <el-dialog title="测试数据" :visible.sync="disposelog" width="45%">
      <el-form ref="dataForm" label-position="left" label-width="190px" style=" margin-left:4%;">
        <el-row>
          <el-col :span="24" :class="[ hidePlanDataFlag ? 'hide-data' : '' ]">
            <el-form-item label="测试数据" class="test-data-row">
              <el-row v-for="(item, index) in testData" :key="index">
                <el-col :span="10">
                  <el-input v-model="item.testData_key" />
                </el-col>
                <el-col :span="10" style="margin-left: 4px;">
                  <el-input v-model="item.testData_value" />
                </el-col>
                <i class="el-icon-delete" style="cursor: pointer;margin-left: 4px;" @click="deleteItem(item, index)" />
                <i class="el-icon-plus" style="cursor: pointer;" @click="addItem" />
              </el-row>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-col :span="24">
        <vue-json-editor v-model="testData" lang="zh" :mode="'code'" />
      </el-col>
      <div style="text-align: center">
        <el-button @click="disposelog=false">取 消</el-button>
        <el-button type="warning" @click="hidePlanDataFlag = !hidePlanDataFlag">{{ hidePlanDataFlag ? '显示' : '隐藏' }}测试数据</el-button>
        <el-button type="primary" @click="saveTestData">确 定</el-button>
      </div>
    </el-dialog>
    <!--测试数据编辑页面 end-->

    <el-dialog title="测试用例" :visible.sync="testcaselog" width="90%">
      <el-row>
        <el-col :span="23">
          <el-transfer
            v-model="testcasedatavalue"
            filterable
            :filter-method="filterMethod"
            :titles="['测试用例库', '已添加测试用例']"
            filter-placeholder="请输入城市拼音"
            :data="testcasedata"
            target-order="push"
            @right-check-change="rightCheck"
          />
        </el-col>
        <el-col :span="1" style="margin-top: 95px;">
          <div style="margin-bottom: 10px">
            <el-button icon="el-icon-arrow-up" circle :disabled="upDownDisable" @click="upData" />
          </div>
          <div style="margin-bottom: 10px">
            <el-button icon="el-icon-arrow-down" circle :disabled="upDownDisable" @click="downData" />
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer" style="text-align: right">
        <el-button @click="testcaselog = false">
          取消
        </el-button>
        <el-button type="primary" @click="addCases()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { delall, addUsecases, addManagementCases, runHandleList, caseManagementList, addManagementList, delHandleList, bindingHandleList, addHandleList, addall } from '@/api/testplan'
import vueJsonEditor from 'vue-json-editor'

export default {
  components: {
    vueJsonEditor
  },
  data() {
    return {
      // 隐藏测试数据
      hidePlanDataFlag: false,
      upDownDisable: true,
      // 搜索条件
      dataForm: {
        demoname: ''
      },
      testcasedata: [],
      testcasedatavalue: [],
      testaddCasesvalue: {
        setID: '',
        caseList: []
      },
      commonPageSetting: {
        entityTitle: '该测试集名称' // 当前页面的对象名称
      },
      set_id: '',
      // 测试用例弹窗
      testcaselog: false,
      // 测试数据弹窗
      disposelog: false,
      // 默认访问第一个页面
      runHandleName: 'first',
      // 管理集合用例
      runHandletableData: [],
      runaddletableData: [],
      // 测试数据
      testData: [],
      Usecasedata: {
        map_id: '',
        testdata_set: ''
      },
      // 管理集合用例id
      runHandlevaluepinid: '',
      pageSize: 10, // 每页大小默认值
      pageIndex: 1, // 默认第一页
      totalPage: 0
    }
  },
  computed: {
    // 管理用例集分页数据
    runHandletablepageData() {
      return this.runHandletableData.slice((this.pageIndex - 1) * this.pageSize, this.pageIndex * this.pageSize)
    },
    // 管理用例集分页数据总数
    runHandletabletotal() {
      return this.runHandletableData.length
    },
    // 用例集分页数据
    runaddtablepageData() {
      return this.runaddletableData.slice((this.pageIndex - 1) * this.pageSize, this.pageIndex * this.pageSize)
    },
    // 用例集分页数据总数
    runaddletabletotal() {
      return this.runaddletableData.length
    }
  },
  // 获取
  mounted() {
    const planName = this.$route.query.planName
    const title = '测试集管理'
    const route = Object.assign({}, this.$route, { title: `${title} - ${planName}` })
    this.$store.dispatch('tagsView/updateVisitedView', route)
    document.title = `${title} - ${planName}`
    this.runHandle()
    this.runHandleData()
  },
  methods: {
    // 表格排序
    runHandletableSortChange({ column, prop, order }) {
      if (order === null) {
        this.handleFilter()
        return false
      }
      this.runHandletableData.sort(function(a, b) {
        return order === 'ascending' ? a[prop] - b[prop] : b[prop] - a[prop]
      })
    },
    runaddtableSortChange({ column, prop, order }) {
      if (order === null) {
        this.handleFilter()
        return false
      }
      this.runaddletableData.sort(function(a, b) {
        return order === 'ascending' ? a[prop] - b[prop] : b[prop] - a[prop]
      })
    },
    rightCheck(selectionKeys, changeKeys) {
      this.tempSelectionKeys = selectionKeys
      if (selectionKeys.length > 0) {
        this.upDownDisable = false
      } else {
        this.upDownDisable = true
      }
    },
    // 穿梭框排序
    upData() {
      // if (this.tempSelectionKeys.length > 1) {
      //   this.$message({
      //     type: 'warning',
      //     message: '仅支持单选调顺序'
      //   })
      //   return
      // }
      if (this.tempSelectionKeys.length > 2) {
        this.$message({
          type: 'warning',
          message: '仅只能选择两条数据调顺序'
        })
        return
      }
      let indexNum = 0
      for (let i = 0; i < this.tempSelectionKeys.length; i++) {
        indexNum = this.testcasedatavalue.indexOf(this.tempSelectionKeys[i])
        if (indexNum > 0) {
          this.testcasedatavalue.splice(indexNum - 1, 0, this.tempSelectionKeys[i])
          this.testcasedatavalue.splice(indexNum + 1, 1)
        }
      }
    },

    downData() {
      if (this.tempSelectionKeys.length > 2) {
        this.$message({
          type: 'warning',
          message: '仅只能选择两条数据调顺序'
        })
        return
      }
      if (this.tempSelectionKeys.length === 1) {
        let indexNum = 0
        for (let i = 0; i < this.tempSelectionKeys.length; i++) {
          indexNum = this.testcasedatavalue.indexOf(this.tempSelectionKeys[i])
          if (indexNum > -1 && indexNum !== this.testcasedatavalue.length - 1) {
            this.testcasedatavalue.splice(indexNum + 2, 0, this.tempSelectionKeys[i])
            this.testcasedatavalue.splice(indexNum, 1)
          }
        }
      } else if (this.tempSelectionKeys.length === 2) {
        let indexNum = 0
        for (let i = 0; i < this.tempSelectionKeys.length; i++) {
          indexNum = this.testcasedatavalue.indexOf(this.tempSelectionKeys[i])
          if (indexNum > -1 && indexNum !== this.testcasedatavalue.length - 1) {
            this.testcasedatavalue.splice(indexNum + 3, 0, this.tempSelectionKeys[i])
            this.testcasedatavalue.splice(indexNum, 1)
          }
        }
      }
    },

    // 数据
    runaddtablepageFilter() {
      const data = []
      Object.assign(data, this.runaddletableData)
      this.runaddletableData = this.selfHandleFilter(data)
    },
    // 管理用例集条件查询
    handleFilter() {
      const data = []
      Object.assign(data, this.runHandletableData)
      this.runHandletableData = this.selfHandleFilter(data)
    },
    // 详细的过滤操作，需要覆写此方法
    selfHandleFilter(data) {
      if (this.dataForm.demoname !== '') {
        data = data.filter(item => item.set_name.indexOf(this.dataForm.demoname) !== -1)
      }
      if (this.dataForm.demoname === '') {
        this.handleClick()
      }
      return data
    },
    // 表格
    selectRowHandle(selection) {
      this.selectIds = []
      this.selectmapIds = []
      const self = this
      selection.forEach(function(row) {
        self.selectmapIds.push(row.map_id)
        self.selectIds.push(row.id)
      })
    },
    // 拿数据
    runHandle() {
      bindingHandleList({ plan_id: this.$route.query.id }).then(response => {
        this.runHandletableData = response.data.reverse()
        this.runHandlevaluepinid = this.$route.query.id
      })
    },
    // 调转刷新
    handleClick() {
      this.dataForm.demoname = ''
      this.runHandleData()
      this.runHandle()
    },
    // 获取测试集
    runHandleData() {
      const params = {}
      runHandleList(params).then(response => {
        this.runaddletableData = response.data.reverse()
      })
    },
    // 前端分页： 当前页码改变
    handleCurrentChange(val) {
      this.pageIndex = val
    },
    // 前端分页：分页大小变化
    handleSizeChange(val) {
      this.pageSize = val
    },
    // 批量删除操作测试用例集
    batchrunHandle(key) {
      if (this.selectIds.length === 0) {
        this.$message.warning('请先选择至少一行数据!')
        return
      }
      this.$confirm('是否批量删除选择的共 ' + this.selectIds.length + ' 条数据？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delall({ plan_id: this.runHandlevaluepinid }, this.selectmapIds).then(response => {
          this.runHandle()
          this.$message.success('删除成功')
        })
      }).catch(() => {
      })
    },
    // 删除
    deleterunHand(row) {
      this.$confirm('是否删除' + this.commonPageSetting.entityTitle + ' 【' + row.set_name + '】 ?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const n = []
        n.push(row.map_id)
        delHandleList({ plan_id: this.runHandlevaluepinid }, n).then(response => {
          this.runHandle()
          this.$message.success('删除成功')
        })
      }).catch(() => {
      })
    },
    // 保存绑定用例集
    runHandleOK(row) {
      const n = []
      n.push(row.id)
      addHandleList({ plan_id: this.runHandlevaluepinid }, n).then(response => {
        this.$message.success('保存成功')
      })
    },
    // 批量添加操作测试用例集
    batchaddHandle(key) {
      if (this.selectIds.length === 0) {
        this.$message.warning('请先选择至少一行数据!')
        return
      }
      this.$confirm('是否批量添加选择的共 ' + this.selectIds.length + ' 条数据？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        addall({ plan_id: this.runHandlevaluepinid }, this.selectIds).then(response => {
          this.runHandle()
          this.runHandleData()
          this.$message.success('添加成功')
        })
      }).catch(() => {
      })
    },
    // 测试数据窗口打开
    testdatalog(row) {
      this.hidePlanDataFlag = false
      this.testData = []
      const n = []
      this.disposelog = true
      this.Usecasedata.map_id = row.map_id
      if (row.testdata_set !== {} && row.testdata_set.length !== 0) {
        for (const key in JSON.parse(row.testdata_set)) {
          n.push({
            key: key,
            value: JSON.parse(row.testdata_set)[key]
          })
        }
        for (let i = 0; i < n.length; i++) {
          this.testData.push({
            testData_key: n[i].key,
            testData_value: n[i].value
          })
        }
      }
      if (this.testData.length === 0) {
        this.addItem()
      }
    },
    saveTestData() {
      const n = {}
      for (let i = 0; i < this.testData.length; i++) {
        if (this.testData[i].testData_key !== undefined && this.testData[i].testData_key.length > 0) {
          n[this.testData[i].testData_key] = this.testData[i].testData_value
        }
      }
      this.Usecasedata.testdata_set = n
      addUsecases(this.Usecasedata).then(response => {
        this.$message.success('更新成功')
        this.disposelog = false
        this.handleClick()
      })
    },
    // 添加测试数据表单
    addItem() {
      this.testData.push({
        testData_key: '',
        testData_value: ''
      })
    },
    // 删除测试数据表单
    deleteItem(item, index) {
      this.testData.splice(index, 1)
      if (this.testData.length === 0) {
        this.addItem()
      }
    },
    // 测试用例按钮事件
    caseCountclick(row) {
      this.testcasedatavalue = []
      this.testcasedata = []
      this.testcaselog = true
      this.set_id = row.id
      addManagementList({ set_id: row.id }).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.testcasedata.push({
            label: response.data[i].case_title + '----' + response.data[i].classed_path + '----' + response.data[i].creator_name,
            key: response.data[i].id,
            pinyin: response.data[i].case_title + '----' + response.data[i].classed_path + '----' + response.data[i].creator_name
          })
        }
      })
      caseManagementList({ set_id: row.id }).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.testcasedata.push({
            label: response.data[i].case_title + '----' + response.data[i].classed_path + '----' + response.data[i].creator_name,
            key: response.data[i].id,
            pinyin: response.data[i].case_title + '----' + response.data[i].classed_path + '----' + response.data[i].creator_name
          })
          this.testcasedatavalue.push(response.data[i].id)
        }
      })
    },
    // 穿梭框
    filterMethod(query, item) {
      return item.pinyin.indexOf(query) > -1
    },
    addCases() {
      this.testaddCasesvalue.caseList = this.testcasedatavalue
      this.testaddCasesvalue.setID = this.set_id
      addManagementCases(this.testaddCasesvalue).then(response => {
        this.$message.success('保存成功')
        this.testcaselog = false
        this.handleClick()
      })
    }
  }
}
</script>

<style scoped>
  /deep/ .el-transfer-panel{
    width: 40%;
    height:100%;
  }
  .el-transfer-panel__list.is-filterable{
    height: 80%;
  }

  /deep/ .jsoneditor-vue{
    height:260px;
    margin-left: 2%;
    margin-right: 2%;
    margin-bottom: 10px;
  }
  .test-data-row .el-row+.el-row {
    margin-top: 10px;
  }
  .hide-data {
    display: none;
  }
</style>
